package fenae.juri;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import lumis.portal.PortalException;
import lumis.portal.UnexpectedException;
import lumis.portal.dao.jdbc.ITransactionJdbc;
import lumis.util.ITransaction;
import lumis.util.PortalUtil;



public class VotacaoTrabalhoDaoJdbc {
	public void registraTrabalho(String trabalhouid, String usuariouid,
			java.util.Date data, String juriuid, ITransaction transaction)
			throws PortalException {
		try {
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection
					.prepareStatement("update trabalho set totalVotos = totalVotos + 1 where trabalhouid = ?");
			try {
				statement.setString(1, trabalhouid);
				statement.executeUpdate();
				statement.close();
				String votacaotrabalhouid = PortalUtil.generateNewGuid();
				statement = connection.prepareStatement("insert into votacaotrabalho (votacaotrabalhouid, trabalhouid, usuariouid, datavotacao, juriuid) values(?,?,?,?,?)");
				statement.setString(1, votacaotrabalhouid);
				statement.setString(2, trabalhouid);
				statement.setString(3, usuariouid);
				statement.setDate(4, new java.sql.Date(data.getTime()));
				statement.setString(5, juriuid);
				statement.executeUpdate();
			} finally {
				statement.close();
			}
		} catch (PortalException e) {
			throw new UnexpectedException(e);
		} catch (Exception e) {
			throw new UnexpectedException(e);
		}
	}

	public boolean verificaUsuarioVoto(String usuariouid, String juriuid,
			ITransaction transaction) throws PortalException {
		try {
			String votacaousuariouid = null;
			ITransactionJdbc daoTransactionJdbc = (ITransactionJdbc) transaction;
			Connection connection = daoTransactionJdbc.getConnection();

			PreparedStatement statement = connection.prepareStatement("select votacaotrabalhouid from votacaotrabalho where usuariouid = ? and juriuid = ?");
			try {
				statement.setString(1, usuariouid);
				statement.setString(2, juriuid);
				ResultSet resultSet = statement.executeQuery();
				try {
					if (resultSet.next()) {
						votacaousuariouid = resultSet.getString("votacaotrabalhouid");
					}
				} finally {
					resultSet.close();
				}
				statement.close();
			} finally {
				statement.close();
			}

			return votacaousuariouid != null;
		} catch (PortalException e) {
			throw new UnexpectedException(e);
		} catch (Exception e) {
			throw new UnexpectedException(e);
		}

	}
}
